package edu.whut.mall.common.util;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class CommonUtil {


    @SuppressWarnings("unchecked")
    public static Map<String, String> parseXml(String xml) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        Document document = DocumentHelper.parseText(xml);
        Element root = document.getRootElement();
        List<Element> elementList = root.elements();
        for (Element e : elementList)
            map.put(e.getName(), e.getText());
        return map;
    }


    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if(index != -1){
                return ip.substring(0,index);
            }else{
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            return ip;
        }
        return request.getRemoteAddr();
    }


    public static String getOrderNumber() {
        int r1 = (int) (Math.random() * (10));//产生2个0-9的随机数
        int r2 = (int) (Math.random() * (10));
        int r3 = (int) (Math.random() * (10));
        long now = System.currentTimeMillis();//一个13位的时间戳
        return "t"+r1 + r2+ r3+ now ;
    }

    public static String getSubOrderNumber() {
        int r1 = (int) (Math.random() * (10));//产生2个0-9的随机数
        int r2 = (int) (Math.random() * (10));
        int r3 = (int) (Math.random() * (10));
        long now = System.currentTimeMillis();//一个13位的时间戳
        return r1 + r2 + r3 + now + "";
    }

    public static String getOutRefundNo() {
        int r1 = (int) (Math.random() * (10));//产生2个0-9的随机数
        int r2 = (int) (Math.random() * (10));
        long now = System.currentTimeMillis();//一个13位的时间戳
        return "f"+r1 + r2 + now + "";
    }

    public static String getPartnerTradeNo() {
        int r1 = (int) (Math.random() * (10));//产生2个0-9的随机数
        int r2 = (int) (Math.random() * (10));
        long now = System.currentTimeMillis();//一个13位的时间戳
        return "c"+r1 + r2 + now + "";
    }

    public static String getWalletDetailNo() {
        // 产生3个0-9的随机数
        int r1 = (int) (Math.random() * (10));
        int r2 = (int) (Math.random() * (10));
        int r3 = (int) (Math.random() * (10));
        // 产生一个13位的时间戳
        long now = System.currentTimeMillis();
        return r1 + r2 + r3 + now + "";
    }
}